package com.ruoyi.system.client.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.client.CsQaqApiClientService;
import com.ruoyi.system.client.ServerChanIm;
import com.ruoyi.system.constant.MessageGenerator;
import com.ruoyi.system.domain.CsOrnamentName;
import com.ruoyi.system.domain.csqaq.*;
import com.ruoyi.system.mapper.CsOrnamentNameMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CsQaqApiClientServiceImpl implements CsQaqApiClientService {
    // 请求地址
    private static final String BASE_URL = "https://api.csqaq.com/api/v1";

    /**
     * 获取Steam API的TOKEN
     */
    private static final String API_TOKEN = "JLFP7107M3T942C8G0H6H096";
    private static final String API_TOKEN1 = "QUPAN1J7K6Z0M0V642N1E7I8";
    private static final String API_TOKEN2 = "MOIOY1M783F9H2D8W065B8L5";
    private static final String API_TOKEN3 = "JYYNO1T7H6N0J2K7G8Y9H2D8";
    private static final String API_TOKEN4 = "QBVOB137E6Y0L2G7X8W9K6C6";

    @Autowired
    private ServerChanIm serverChanIm;

    @Autowired
    private static CsOrnamentNameMapper csOrnamentNameMapper;


    // 获取csqaq首页数据
    @Override
    public HomeDateResponse getCsQaqCurrentData() {
        String responseDateJson = HttpUtils.sendGet(BASE_URL + "/current_data?type=init", null, MediaType.TEXT_PLAIN_VALUE, callback -> {
            callback.setRequestProperty("Host", "api.csqaq.com");
        });
        HomeDateResponse homeDateResponse = JSONObject.parseObject(responseDateJson, HomeDateResponse.class);
        return homeDateResponse;
    }

    @Override
    public DynamicResponse getCsQaqSubData(String apiToken) {
        String s = HttpUtils.sendGet(BASE_URL + "/sub_data", "id=1&type=daily", MediaType.TEXT_PLAIN_VALUE, callback -> {
            callback.setRequestProperty("ApiToken", apiToken);
            callback.setRequestProperty("Host", "api.csqaq.com");
        });
        return null;
    }

    @Override
    public DynamicResponse getCsQaqInventoryDynamic(String apiToken, Long taskId) {
        JSONObject requestBodyJson = new JSONObject();
        requestBodyJson.put("page_index", 1);
        requestBodyJson.put("page_size", 50);
        requestBodyJson.put("task_id", taskId);
        requestBodyJson.put("type", "ALL");
//        requestBodyJson.put("search", "武器箱");
        String requestBody = requestBodyJson.toString();
        String apiToken1 = HttpUtils.sendPost(BASE_URL + "/task/get_task_business", requestBody, MediaType.APPLICATION_JSON_VALUE, callback -> {
            callback.setRequestProperty("ApiToken", apiToken);
            callback.setRequestProperty("Host", "api.csqaq.com");
        });
        System.out.println(apiToken1);
        return null;
    }

    @Override
    public GoodsInfoResponse getCsQaqGoodsInfoByGoodId(String apiToken, Long goodId) {
        String response = HttpUtils.sendGet(BASE_URL + "/info/good", "id=" + goodId,
                MediaType.TEXT_PLAIN_VALUE, callback -> {
                    callback.setRequestProperty("ApiToken", apiToken);
                    callback.setRequestProperty("Host", "api.csqaq.com");
                });
        GoodsInfoResponse goodsInfoResponse = JSONObject.parseObject(response, GoodsInfoResponse.class);
        return goodsInfoResponse;
    }

    @Override
    public GoodsInfoBySearchResponse getCsQaqGoodsInfoBySearch(String apiToken, String search) {
        JSONObject requestBodyJson = new JSONObject();
        requestBodyJson.put("page_index", 1);
        requestBodyJson.put("page_size", 50);
        requestBodyJson.put("search", search);
        String requestBody = requestBodyJson.toString();
        String response = HttpUtils.sendPost(BASE_URL + "/info/get_good_id", requestBody, MediaType.APPLICATION_JSON_VALUE, callback -> {
            callback.setRequestProperty("ApiToken", apiToken);
            callback.setRequestProperty("Host", "api.csqaq.com");
        });
        return JSONObject.parseObject(response, GoodsInfoBySearchResponse.class);
    }

    public static void main(String[] args) {
        CsQaqApiClientService csQaqApiClientService = new CsQaqApiClientServiceImpl();
//        csQaqApiClientService.getCsQaqSubData(API_TOKEN);
//        csQaqApiClientService.getCsQaqInventoryDynamic(API_TOKEN, 6185L);
        HomeDateResponse csQaqCurrentData = csQaqApiClientService.getCsQaqCurrentData();
        Alteration alteration = csQaqCurrentData.getData().getAlteration().get(0);
        String s = MessageGenerator.generateMessage(alteration);
        ServerChanImImpl serverChanIm = new ServerChanImImpl();
        serverChanIm.scSend("饰品异动", s, "CS");
    }

    public void updateOrnamentNames() {
        for (int i = 1; i < 1000; i++) {
            GoodsInfoResponse csQaqGoodsInfoByGoodId = getCsQaqGoodsInfoByGoodId(API_TOKEN, Long.valueOf(i));
            // 添加1000毫秒延迟
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.err.println("线程延迟被中断: " + e.getMessage());
            }

            if (csQaqGoodsInfoByGoodId.getCode() != 200) {
                continue;
            }
            GoodsInfo goodsInfo = csQaqGoodsInfoByGoodId.getData().getGoodsInfo();
            if (ObjectUtils.isEmpty(goodsInfo)) {
                continue;
            }
            CsOrnamentName csOrnamentName = csOrnamentNameMapper.selectOne(new QueryWrapper<CsOrnamentName>()
                    .eq("market_hash_name", goodsInfo.getMarketHashName()));
            if (ObjectUtils.isEmpty(csOrnamentName)) {
                continue;
            }
            csOrnamentNameMapper.update(null, new LambdaUpdateWrapper<CsOrnamentName>()
                    .eq(CsOrnamentName::getId, csOrnamentName.getId())
                    .set(CsOrnamentName::getCsQaqId, goodsInfo.getId()));
        }
    }

    public void updateOrnamentNames1(CsQaqApiClientService apiClientService, CsOrnamentNameMapper mapper) {
        List<String> tokens = Arrays.asList(API_TOKEN, API_TOKEN1, API_TOKEN2, API_TOKEN3, API_TOKEN4);
        for (int i = 0; i < 10000; i++) {
//            CsOrnamentName csOrnamentName1 = mapper.selectOne(new LambdaQueryWrapper<CsOrnamentName>()
//                    .eq(CsOrnamentName::getCsQaqId, i));
            CsOrnamentName csOrnamentName1 = mapper.selectOne(new LambdaQueryWrapper<CsOrnamentName>()
                    .isNull(CsOrnamentName::getCsQaqId)
                    .lt(CsOrnamentName::getUpdateDate, "2025-10-13 10:58:39")
                    .last("LIMIT 1"));
            if (ObjectUtils.isEmpty(csOrnamentName1)) {
                continue;
            }

            String currentToken = tokens.get(i % tokens.size());
            GoodsInfoBySearchResponse csQaqGoodsInfoBySearch = null;
            try {
                csQaqGoodsInfoBySearch = apiClientService.getCsQaqGoodsInfoBySearch(currentToken, csOrnamentName1.getMarketHashName());
            } catch (Exception ex) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.err.println("线程延迟被中断: " + e.getMessage());
                }
                continue;
            }

//            GoodsInfoResponse csQaqGoodsInfoByGoodId = apiClientService.getCsQaqGoodsInfoByGoodId(currentToken, Long.valueOf(i));
            // 添加500毫秒延迟
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.err.println("线程延迟被中断: " + e.getMessage());
            }
            if (csQaqGoodsInfoBySearch.getCode() != 200) {
                continue;
            }
            if (ObjectUtils.isEmpty(csQaqGoodsInfoBySearch)) {
                continue;
            }
            Map<String, GoodsInfoBySearchResponse.GoodsInfoBySearch> data = csQaqGoodsInfoBySearch.getData().getData();

            if (ObjectUtils.isEmpty(data)) {
                mapper.update(null, new LambdaUpdateWrapper<CsOrnamentName>()
                        .eq(CsOrnamentName::getMarketHashName, csOrnamentName1.getMarketHashName())
                        .set(CsOrnamentName::getCsQaqId, -1)
                        .set(CsOrnamentName::getUpdateDate, new Date()));
                continue;
            }
            data.forEach((k, v) -> {
                mapper.update(null, new LambdaUpdateWrapper<CsOrnamentName>()
                        .eq(CsOrnamentName::getMarketHashName, v.getMarketHashName())
                        .eq(CsOrnamentName::getName, csOrnamentName1.getName())
                        .set(CsOrnamentName::getCsQaqId, v.getId())
                        .set(CsOrnamentName::getUpdateDate, new Date()));
                mapper.update(null, new LambdaUpdateWrapper<CsOrnamentName>()
                        .eq(CsOrnamentName::getName, csOrnamentName1.getName())
                        .set(CsOrnamentName::getUpdateDate, new Date()));
            });
//            CsOrnamentName csOrnamentName = mapper.selectOne(new QueryWrapper<CsOrnamentName>()
//                    .eq("market_hash_name", goodsInfo.getMarketHashName()));
//            if (ObjectUtils.isEmpty(csOrnamentName)) {
//                continue;
//            }
//            mapper.update(null, new LambdaUpdateWrapper<CsOrnamentName>()
//                    .eq(CsOrnamentName::getId, csOrnamentName.getId())
//                    .set(CsOrnamentName::getCsQaqId, goodsInfo.getId()));
        }
    }

}
